package com.mayo.feaf;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.mayo.feaf.comun.BaseActivity;
import com.mayo.feaf.comun.ComunActivity;
import com.mayo.feaf.comun.ComunUtilidades;
import com.mayo.feaf.comun.TratamientoImagenComun;
import com.mayo.feaf.json.JSONParser;
import com.mayo.feaf.object.IndumentariaObject;

public class GaleriaIndumentariasActivity extends BaseActivity {

	private GridView gridview;
	public ImageAdapter adapter;
	public JSONParser jParser = new JSONParser();
	public static JSONArray indumentarias = null;
	public ProgressDialog pDialog;
	
	public final String TAG_SUCCESS = "success";
	public final String TAG_INDUMENTARIAS = "indumentarias";
	public final String TAG_ID = "id";
	public final String TAG_NOMBRE = "nombre_indumentaria";
	public final String TAG_FECHA = "fecha_registro";
	public final String TAG_DESC_MUJER = "descripcion_indumentaria_mujer";
	public final String TAG_DESC_HOMBRE = "descripcion_indumentaria_hombre";
	public final String TAG_TIPO = "tipo_indumentaria";
	public final String TAG_CIUDAD = "nombre_ciudad";
	public final String TAG_PROVINCIA = "nombre_provincia";
	public final String TAG_COMUNIDAD = "nombre_comunidad";
	public final String TAG_COMENTARIOS = "comentarios_indumentaria";
	public final String TAG_RUTA_IMAGENES = "ruta_imagenes";
	public final String TAG_IMAGEN_PREVIA = "imagen_previa";
	public final String TAG_LATITUD = "latitud";
	public final String TAG_LONGITUD = "longitud";
	
	private String comunidad;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.galeria_indumentarias);
		
		gridview = (GridView) findViewById(R.id.gridview);
		gridview.setNumColumns(2);

	    gridview.setOnItemClickListener(new OnItemClickListener() {
	        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
	            Toast.makeText(GaleriaIndumentariasActivity.this, "" + position, Toast.LENGTH_SHORT).show();
	        }
	    });
		
		if (getIntent().getExtras() != null) {
			Bundle todosParametros = getIntent().getExtras();
			comunidad = todosParametros.getString("comunidad");
		}
		actionBar.setTitle(R.string.tit_galeria_indumentarias);
		String nombreComunidad = ComunActivity.getComunidadFromId(Integer.parseInt(comunidad));
		actionBar.setSubtitle(nombreComunidad);
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE
				| ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_HOME_AS_UP
				| ActionBar.DISPLAY_SHOW_CUSTOM);
		
		new LoadAllIndumentarias().execute(comunidad);
	  }
	
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            this.finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    /**
	 * Background Async Task to Load all product by making HTTP Request
	 * */
	class LoadAllIndumentarias extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(GaleriaIndumentariasActivity.this);
			pDialog.setMessage("Cargando el listado de agrupaciones. Por favor espere...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting All products from url
		 * */
		protected String doInBackground(String... args) {
			String error = "0";
			List<NameValuePair> params;
			JSONObject json = new JSONObject();
			try {
				params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("comunidad", args[0]));
				json = jParser.makeHttpRequest(ComunUtilidades.URL_GET_INDUMENTARIAS, "GET", params);
				Log.d("Todas las agrupaciones: ", json.toString());
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					indumentarias = json.getJSONArray(TAG_INDUMENTARIAS);
					adapter = new ImageAdapter(indumentarias.length(),
							getApplicationContext());

					// looping through All Products
					for (int i = 0; i < indumentarias.length(); i++) {
						JSONObject c = indumentarias.getJSONObject(i);
						
						int id = c.getInt(TAG_ID);
						String nombre = c.getString(TAG_NOMBRE);
						String fechaRegistro = c.getString(TAG_FECHA);
						String comunidad = c.getString(TAG_COMUNIDAD);
						String provincia = c.getString(TAG_PROVINCIA);
						String ciudad = c.getString(TAG_CIUDAD);
						String descMujer = c.getString(TAG_DESC_MUJER);
						String descHombre = c.getString(TAG_DESC_HOMBRE);
						String tipo = c.getString(TAG_TIPO);
						String comentarios = c.getString(TAG_COMENTARIOS);
						String ruta = c.getString(TAG_RUTA_IMAGENES);
						String imagenPrevia = ComunUtilidades.SERVIDOR_IMAGENES + c.getString(TAG_IMAGEN_PREVIA);
						String latitud = c.getString(TAG_LATITUD);
						String longitud= c.getString(TAG_LONGITUD);
						
						IndumentariaObject indu = new IndumentariaObject(id, nombre, fechaRegistro, comunidad, provincia, ciudad, descMujer, descHombre, tipo, comentarios, ruta, imagenPrevia,
								latitud, longitud);
						
						adapter.addItem(indu);
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
				error = "1";
			} catch (RuntimeException e) {
				e.printStackTrace();
				error = "1";
			}

			return error;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(final String error) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
			 public void run() {
				if (error.equals("0")) {
					gridview.setAdapter(adapter);
				} else {
					Toast.makeText(getApplicationContext(), getString(R.string.error_conexion),
							Toast.LENGTH_LONG).show();
				}
			 }
			});

		}
	}
	
	public class ImageAdapter extends BaseAdapter {
		public final ViewHolder holder = new ViewHolder();
		private ArrayList<IndumentariaObject> indumentarias = new ArrayList<IndumentariaObject>();
	    private Context mContext;
	    private LayoutInflater inflater;
	    
		private HashMap<Integer, ImageView> views;
		private HashMap<Integer, ProgressBar> viewsProgress;
	    private HashMap<String,Bitmap> oldPicts = new  HashMap<String,Bitmap>();
	    boolean auto;

	    private final String BUNDLE_URL = "url";
	    private final String BUNDLE_BM = "bm";
	    private final String BUNDLE_POS = "pos";
	    private final String BUNDLE_ID = "id";

		public ImageAdapter(int size, Context context) {
			inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			this.mContext = context;
			inflater = LayoutInflater.from(context);
			views = new HashMap<Integer, ImageView>();
			viewsProgress = new HashMap<Integer, ProgressBar>();
		}
		
		public void addItem(final IndumentariaObject indumentaria) {
			indumentarias.add(indumentaria);
			notifyDataSetChanged();
		}
		
	    public ImageAdapter(Context context) {
	    	inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			this.mContext = context;
			inflater = LayoutInflater.from(context);
	    }

	    public int getCount() {
	        return indumentarias.size();
	    }

	    public Object getItem(int position) {
	        return indumentarias.get(position);
	    }

	    public long getItemId(int position) {
	        return 0;
	    }

	    // create a new ImageView for each item referenced by the Adapter
	    public View getView(final int position, View grid, ViewGroup parent) {
	    	ImageView imageView;
	    	TextView nombre = null;
	    	ProgressBar progress = null;
	         if(grid == null) {
	             grid = inflater.inflate(R.layout.celda_indumentaria, null);
	             imageView =  (ImageView)grid.findViewById(R.id.imageIndu);
	             nombre =  (TextView)grid.findViewById(R.id.textIndu);
	             progress = (ProgressBar) grid.findViewById(R.id.progress);

	             grid.setTag(imageView);

	             IndumentariaObject indumentaria = (IndumentariaObject) getItem(position);
	         
	             nombre.setText(indumentaria.getNombre());

	      // put infos in bundle and send to the LoadImage class
	             Bundle b = new Bundle();
	             b.putString(BUNDLE_URL, indumentaria.getImagenPrevia());
	             b.putInt(BUNDLE_POS, position);
	             b.putString(BUNDLE_ID, String.valueOf(indumentaria.getId()));
	             views.put(position, imageView);
	        	 viewsProgress.put(position, progress);
	        
	             new DownloadImagePrevia().execute(b);
//	          	imageView.setImageResource(mThumbIds[position]);
	             imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
	             
	             imageView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(getApplicationContext(), IndumentariasDetalleActivity.class);
						Bundle contenedor=new Bundle();
						contenedor.putParcelable("indumentaria", indumentarias.get(position));
						intent.putExtras(contenedor);
						startActivity(intent);
					}
				});

	         } else {
	             imageView = (ImageView)grid.getTag();
	          }
	         return grid;

	    }

	    // references to our images
//	    private Integer[] mThumbIds = {
//	            R.drawable.indu01, R.drawable.indu02,
//	            R.drawable.indu03, R.drawable.indu04,
//	            R.drawable.indu05, R.drawable.indu06,
//	            R.drawable.indu07, R.drawable.indu08,
//	            
//	    };
	    
	    public class DownloadImagePrevia extends AsyncTask<Bundle, Bundle, Bundle> {
			// Do the long-running work in here

			public Bundle doInBackground(Bundle... b) {
				Bitmap bm = null;
				try {
					//cache: for better performance, check if url alredy exists
		            if (oldPicts.get(b[0].getString(BUNDLE_ID)) == null){
		            	bm = TratamientoImagenComun.decodeSampledBitmapFromUri(b[0].getString(BUNDLE_URL), 
		            			getResources().getIntArray(R.array.grid_celda)[1], getResources().getIntArray(R.array.grid_celda)[1]);
		                oldPicts.put(b[0].getString(BUNDLE_ID),bm);
		            } else {
		                bm = oldPicts.get(b[0].getString(BUNDLE_ID));
		            }
		            Bundle bundle = new Bundle();
		            bundle.putParcelable(BUNDLE_BM, bm);
		            bundle.putInt(BUNDLE_POS, b[0].getInt(BUNDLE_POS));

		            return bundle;
				} catch (NullPointerException e) {
				} catch (Exception e) {
				}
				return null;
			}

			// This is called when doInBackground() is finished
			public void onPostExecute(final Bundle result) {
				super.onPostExecute(result);
				 runOnUiThread(new Runnable() {
					 public void run() {
						 //get picture saved in the map + set
						 ImageView view = views.get(result.getInt(BUNDLE_POS));
						 ProgressBar progress = viewsProgress.get(result.getInt(BUNDLE_POS));
						 Bitmap bm = (Bitmap) result.getParcelable(BUNDLE_BM);
						 if (bm != null){ //if bitmap exists...
							 view.setImageBitmap(bm);
							 progress.setVisibility(ProgressBar.GONE);
							 view.setImageBitmap(bm);
							 view.setVisibility(ImageView.VISIBLE);
						 } else { //if not picture, display the default ressource
							 view.setImageResource(R.drawable.ic_launcher);
							 progress.setVisibility(ProgressBar.GONE);
							 view.setVisibility(ImageView.VISIBLE);
						 }
					 }
				 });
			}
		}
	}
	
	public static class ViewHolder {
		private ImageView imagen;
		private TextView nombre;
		private String urlImagen;
	}
	
}
